import http from '@ohos.net.http';
import { Cache } from '../../utils/cache';
import { Logger } from '../../utils/log';
import { Request } from '../types/Request';

const cache = new Cache();
const logger = new Logger('HTTP');
const IN_MS = 60 * 1000; // 一分钟的毫秒数

export async function fetchHtml(request: Request): Promise<string> {
  const url = typeof request === 'string' ? request : request.url;
  const method = typeof request === 'string' ? http.RequestMethod.GET : request.method || http.RequestMethod.GET;
  const headers = typeof request === 'string' ? {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
  } : request.headers || {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
  };
  const body = typeof request === 'string' ? undefined : request.params;
  const timeout = typeof request === 'string' ? IN_MS : request.timeout || IN_MS;

  const cachedContent = await cache.get(url);
  if (cachedContent) {
    logger.info(`Cache hit for URL: ${url}`);
    return cachedContent;
  }

  logger.info(`Requesting URL: ${url}`);
  const httpRequest = http.createHttp();
  try {
    const startTime = Date.now();
    const response = await httpRequest.request(url, {
      method,
      timeout,
      header: headers,
      extraData: body,
      expectDataType: http.HttpDataType.STRING
    } as http.HttpRequestOptions);
    const duration = Date.now() - startTime;
    
    if (response.responseCode === 200) {
      const result = response.result as string;
      logger.info(`Request successful - URL: ${url}, Duration: ${duration}ms, Size: ${result.length} bytes`);
      await cache.set(url, result, IN_MS);
      return result;
    }
    
    logger.error(`Request failed - URL: ${url}, Status: ${response.responseCode}, Duration: ${duration}ms`);
    throw new Error(`HTTP Error: ${response.responseCode}`);
  } catch (error) {
    logger.error(`Request error - URL: ${url}, Error: ${error}`);
    throw error;
  } finally {
    httpRequest.destroy();
  }
}
